package com.limao.DBProvider;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.limao.DBDataClass.CourierGpsDataClass;
import com.limao.DbConnection.DbConnectionManager;
import com.limao.Tool.CacheClass;

public class CourierGpsProvider {
    
    private static class DB_CourierGps_ProviderContainer {
        private static CourierGpsProvider instance = new CourierGpsProvider();
    }
    public static CourierGpsProvider getInstance() {
        return DB_CourierGps_ProviderContainer.instance;
    }    

    private static final String table1="lz_courier_gps";
    //增加记录
    private static final String lz_courier_gps_INSERT = "INSERT INTO "+table1+ " (id,lat,lon,time) VALUES (?,?,?,?)"; 
    
	// 初始化
	private CourierGpsProvider() {}
    
    //增加记录
    public CourierGpsDataClass addCourierGps(int userid,double lat,double lon) 
	{
		Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        CourierGpsDataClass cg=null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(lz_courier_gps_INSERT);
			pstmt.setInt(1, userid);
			pstmt.setDouble(2, lat);
			pstmt.setDouble(3, lon);
			pstmt.setLong(4, CacheClass.getTime());
			pstmt.execute();
			cg = new CourierGpsDataClass();
			cg.lat = lat + "";
			cg.lon = lon + "";
		} catch (Exception e) {
			cg = null;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
        return cg;
	}    
    
    //查出符合某时间段的某配送员GPS列表
	public List<CourierGpsDataClass> getCourierGPSList(int userid,
				Long starttime, Long endtime, Connection con) throws Exception {
		List<CourierGpsDataClass> cgList = new ArrayList<CourierGpsDataClass>(0);
		String sql = "select * from lz_courier_gps where id=?  and time>? and time<?  order by time asc ";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setInt(1, userid);
		pstmt.setLong(2, starttime);
		pstmt.setLong(3, endtime > 1 ? endtime : CacheClass.getTime());
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			CourierGpsDataClass cg = new CourierGpsDataClass();
			cg.id = rs.getInt("id") + "";
			cg.lat = rs.getDouble("lat") + "";
			cg.lon = rs.getDouble("lon") + "";
			cgList.add(cg);
		}
		DbConnectionManager.closeResultSet(rs);
		DbConnectionManager.fastcloseStmt(rs,pstmt);
		return cgList;
	}
}
